<?php 


/**
* 数据库操作类
*/
class Model  
{
		
	public $table;//需要操作的表
	public static $db;//pdo链接对象
	public static $error;//输出错误信息
	public $where='';
	public $order='';
	public $limit='';
	public $field='*';
	function __construct($table='')
	{
		if(!empty($table)){
			$this->table=$table;
		}

		if(!isset(self::$db)){
			try {

			self::$db = new PDO(C('DB_TYPE').":host=".C('DB_HOST').";dbname=".C('DB_NAME').";charset=utf8",C('DB_USERNAME'),C('DB_PASSWORD'));

			}catch(PDOException $e){ 
				// // var_dump($db->errorCode());
				// var_dump($e->getmessage());exit;
				exit("错误代码：".$e->getCode().",错误信息".$e->getmessage());
			}
		}
		
	}

	public function add($data)
	{

		$keys=implode(',', array_keys($data));

		$values= implode("','", array_values($data));

		$sql = "insert into ".$this->table."(".$keys.") values('".$values."')";

		$this->exec($sql);

		return self::$db->lastInsertId();
	}

	//专门查询的方法
	public function query($sql)
	{
		$res = self::$db->query($sql);

		return $res->fetchAll(PDO::FETCH_ASSOC);
	}
	//执行增删改的方法
	public function exec($sql)
	{

		$res = self::$db->exec($sql);
		if(!$res){
			self::$error=self::$db->errorInfo()[2];
		}
		return $res;
	}
	//获取错误信息
	public function getError()
	{
		var_dump(self::$error);
	}

	public function where($data)
	{
		$this->where="where ".$data;
		return $this;
	}

	public function order($data)
	{
		$this->order="order by ".$data;
		return $this;
	}

	public function limit($data)
	{
		$this->limit="limit ".$data;
		return $this;
		
	}

	public function field($data)
	{
		$this->field=$data;
		return $this;
	}

	public function select()
	{
		$sql = "select ".$this->field." from ".$this->table." ".$this->where." ".$this->order." ".$this->limit;

		return $this->query($sql);
	}

}


















 ?>